package com.device.operating.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.device.operating.entity.DataDictionary;
import com.device.operating.entity.Department;
import com.device.operating.entity.Dprole;
import com.device.operating.entity.Func;
import com.device.operating.entity.Role;
import com.device.operating.entity.Ugfunc;
import com.device.operating.entity.Ugfunctype;
import com.device.operating.entity.User;
import com.device.operating.entity.Usergroup;
import com.device.operating.service.DataDictionaryService;
import com.device.operating.service.DepartmentService;
import com.device.operating.service.DproleService;
import com.device.operating.service.FuncService;
import com.device.operating.service.RoleService;
import com.device.operating.service.UgService;
import com.device.operating.service.UgfuncService;
import com.device.operating.service.UgfunctypeService;
import com.device.operating.service.UserService;
import com.device.operating.utils.KeyProvider;
import com.device.operating.utils.TimeStr;

@Controller
public class UserController extends BaseController{

	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="FuncService")
	private FuncService FuncService;
	
	@Resource(name="DepartmentService")
	private DepartmentService DepartmentService;
	
	@Resource(name="DproleService")
	private DproleService DproleService;
	
	@Resource(name="UgfuncService")
	private UgfuncService UgfuncService;
	
	@Resource(name="UgfunctypeService")
	private UgfunctypeService UgfunctypeService;
	
	@Resource(name="UgService")
	private UgService UgService;
	
	@Resource(name="RoleService")
	private RoleService RoleService;
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request){
		HttpSession session=request.getSession();
		if(session.getAttribute("user")!=null){
			return "main.jsp";
		}else{
			return "login.jsp";
		}
	}
	
	
	@RequestMapping("/loginuser")
	public String loginuser(HttpServletRequest request){
		String result="";
		String tel=request.getParameter("tel");
		String password=request.getParameter("password");
		User user=userService.login(tel, password);
		if(user!=null){
			List<String> listfunc=new ArrayList<>();
			List<Usergroup> listug=UgService.querybyuserId(user.getUserId());
			for(Usergroup ug:listug){
				String gpId=ug.getGpId();
				List<Ugfunc> listugfunc=UgfuncService.querybyugIdandugtype(gpId, "0");
				for(Ugfunc uf:listugfunc){
					listfunc.add(uf.getFunccode());
				}
			}
			user.setListfunc(listfunc);
			result="redirect:main";
			HttpSession session=request.getSession();
			session.setAttribute("user", user);
		}else{
			result="login.jsp";
		}
		return result;
	}
	
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request){
		HttpSession session=request.getSession();
		session.invalidate();
		return "login.jsp";
	}
	
	@RequestMapping(value="/adduser",method=RequestMethod.POST)
	@ResponseBody
	public Map adduser(HttpServletRequest request) throws ParseException{
		Map map=new HashMap<>();
		String username=request.getParameter("username");
		List<User> listuser=userService.querybyname(username);
		if(listuser.size()>0){
			map.put("msg", "名字重复");
			return map;
		}		
		String departmentId=request.getParameter("departmentId");
		Department dp=DepartmentService.queryone(departmentId);
		String dpname=dp.getDpname();
		String rootdpId=dp.getRootdpId();
		String rootdpname=dp.getRootdpname();
		String userId=KeyProvider.getPrimaryKey();
		String email=request.getParameter("email");
		String usercode=request.getParameter("usercode");
		String tel=request.getParameter("tel");
		String loctel=request.getParameter("loctel");
		String roleId=request.getParameter("roleId");
		Role role=RoleService.queryone(roleId);
		String rolename=role.getRolename();
		int rolelevel=role.getRolelevel();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String birth=request.getParameter("birthday");
		birth=TimeStr.getfordate(birth);

		Date birthday=null;
		if(birth!="")
			birthday=df.parse(birth);
		
		int ifleader=new Integer(request.getParameter("ifleader")).intValue();
		User user=new User();
		user.setDepartmentId(departmentId);
		user.setDpname(dpname);
		user.setRootdpId(rootdpId);
		user.setRootdpname(rootdpname);
		user.setEmail(email);
		user.setBirthday(birthday);
		user.setLoctel(loctel);
		user.setPassword("8888");
		user.setRoleId(roleId);
		user.setRolename(rolename);
		user.setTel(tel);
		user.setUserId(userId);
		user.setUsername(username);
		user.setIfleader(ifleader);
		user.setRootdpId(rootdpId);
		user.setRolelevel(rolelevel);
		user.setUsercode(usercode);
		userService.addUser(user);
		map.put("msg", "添加成功");
		return map;
	}
	
	//有问题，以后再改！！！！！！！！！！！！！！！！！
	@RequestMapping(value="/deleteuserIds",method=RequestMethod.POST)
	@ResponseBody
	public Map deleteuserIds(HttpServletRequest request){
		Map map=new HashMap<>();
		String deleteuserIds=request.getParameter("deleteuserIds");
		String[] dusers=deleteuserIds.split(",");
		for(int i=0;i<dusers.length;i++){
			List<Usergroup> listug=UgService.querybyuserId(dusers[i]);//这块
			if(listug.size()!=0){
				Usergroup ug=listug.get(0);
				map.put("msg", "该用户:"+ug.getUsername()+",在组:"+ug.getGpname()+",故无法删除!");
				return map;
			}
		}
		for(int i=0;i<dusers.length;i++){
			userService.deleteuser(dusers[i]);
		}
		map.put("msg", "删除成功!");
		return map;
	}
	
	@RequestMapping("/toadduser")
	public String toadduser(HttpServletRequest request,ModelMap map){
		String departmentId=request.getParameter("departmentId");
		Department dp=DepartmentService.queryone(departmentId);
		map.put("department", dp);
		return "org/adduser.jsp";
	}
	
	@RequestMapping("/getrolesofdepartment")
	@ResponseBody
	public List<Dprole> getrolesofdepartment(HttpServletRequest request){
		String departmentId=request.getParameter("departmentId");
		List<Dprole> listdp=DproleService.querybydpId(departmentId);
		return listdp;
	}
	
	@RequestMapping("/main")
	public String main(HttpServletRequest request,ModelMap map){
		User user=getuser(request);
		List<Ugfunctype> listtype=new ArrayList<>();
		List<Ugfunctype> listjsp=new ArrayList<>();
		int gpcount=0;
		List<Usergroup> listgroup=UgService.querybyuserId(user.getUserId());
		for(Usergroup ug:listgroup){
			String gpId=ug.getGpId();
			if(gpcount>0){//俩个组以上
				List<Ugfunctype> listug=UgfunctypeService.querybyugIdandugfuncyupesort(gpId, "0");
				List<Ugfunctype> listls=new ArrayList<>();
				int flag=1;
				for(Ugfunctype uf:listug){
					String functypeId=uf.getFunctypeId();
					for(Ugfunctype ut:listtype){
						if(functypeId.equals(ut.getFunctypeId())){//重复
							flag=0;
							break;
						}
					}
					if(flag==1){
						listls.add(uf);
					}
				}
				listtype.addAll(listls);
				listls.clear();
				flag=1;
				List<Ugfunctype> listugjsp=UgfunctypeService.querybyugIdandugfuncyupesort(gpId, "1");
				for(Ugfunctype uf:listugjsp){
					String functypeId=uf.getFunctypeId();
					for(Ugfunctype ut:listjsp){
						if(functypeId.equals(ut.getFunctypeId())){//重复
							flag=0;
							break;
						}
					}
					if(flag==1){
						listls.add(uf);
					}
				}
				listjsp.addAll(listls);
			}else{
				listtype.addAll(UgfunctypeService.querybyugIdandugfuncyupesort(gpId, "0"));//type为0
				listjsp.addAll(UgfunctypeService.querybyugIdandugfuncyupesort(gpId, "1"));//jsp为1
			}
			gpcount++;
		}
		map.put("listtype", listtype);
		map.put("listjsp", listjsp);
		return "main.jsp";
	}
	
	@RequestMapping("/touserlist")
	public String touserlist(HttpServletRequest request,ModelMap map){
		String departmentId=request.getParameter("departmentId");
		map.put("ysdpId", departmentId);
		return "org/userlist.jsp";
	}
	
	@RequestMapping("/showuserlist")
	@ResponseBody
	public Map showuserlist(HttpServletRequest request,
			@RequestParam(required = false, defaultValue = "1") Integer page,
			 @RequestParam(required = false, defaultValue = "10") Integer rows){
		String departmentId=request.getParameter("departmentId");
		if(departmentId==null||departmentId.equals("")||departmentId.equals("0")){
			return null;
		}
		return userService.queryalluserbydepartmentId(departmentId, page-1, rows,true);
	}
	
	@RequestMapping("/touserdetail")
	public String touserdetail(HttpServletRequest request,ModelMap map){
		String userId=request.getParameter("userId");
		if(userId!=null){//直接过来了，则无需查询NAME
			map.put("userId", userId);
		}
		return "org/userdetail.jsp";
	}
	
	@RequestMapping("/searchuserinfo")
	@ResponseBody
	public User searchuserinfo(HttpServletRequest request){
		String username=request.getParameter("username");
		String usercode=request.getParameter("usercode");
		List<User> list=null;
		if(username==null){
			list=userService.querybyusercode(usercode);
		}else{
			list=userService.querybyname(username);
		}		
		if(list.size()!=0){
			return list.get(0);
		}
		return null;
	}
	
	@RequestMapping("/toedituser")
	public String toedituser(HttpServletRequest request,ModelMap map){
		String userId=request.getParameter("userId");
		User user=userService.queryUser(userId);
		map.put("user", user);
		List<Dprole> listdprole=DproleService.querybydpId(user.getDepartmentId());
		map.put("listdepart", DepartmentService.queryall());
		map.put("listdprole", listdprole);
		return "org/edituser.jsp";
	}
	
	@RequestMapping(value="/edituser",method=RequestMethod.POST)
	@ResponseBody
	public Map edituser(HttpServletRequest request) throws ParseException{
		Map map=new HashMap<>();
		String userId=request.getParameter("userId");
		String departmentId=request.getParameter("departmentId");
		String roleId=request.getParameter("roleId");
		String birth=request.getParameter("birthday");
		String usercode=request.getParameter("usercode");
		String tel=request.getParameter("tel");
		String loctel=request.getParameter("loctel");
		String email=request.getParameter("email");
		String password=request.getParameter("password");
		User user=userService.queryUser(userId);
		Department dp=DepartmentService.queryone(departmentId);
		Role role=RoleService.queryone(roleId);		
		if(!birth.equals("")){
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			birth=TimeStr.getfordate(birth);
			Date birthday=null;
			if(birth!=""){
				birthday=df.parse(birth);
				user.setBirthday(birthday);
			}	
		}	
		if(!password.equals("")){//修改密码
			user.setPassword(password);
		}
		user.setDepartmentId(departmentId);
		user.setDpname(dp.getDpname());
		user.setRootdpId(dp.getRootdpId());
		user.setRootdpname(dp.getRootdpname());
		user.setEmail(email);
		user.setLoctel(loctel);
		user.setRoleId(roleId);
		user.setRolelevel(role.getRolelevel());
		user.setRolename(role.getRolename());
		user.setUsercode(usercode);
		user.setTel(loctel);
		userService.addUser(user);
		map.put("msg", "编辑成功!");
		return map;
	}
}
